﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Utilities
{

    public struct BoxStruct
    {
        public Vector3 Min { get; set; }
        public Vector3 Max { get; set;}

    }
    public static class Extensions
    {
        
        public static float Get(this Vector3 vector, int i)
        {
            switch (i)
            {
                case 0:
                    return vector.X;
                case 1:
                    return vector.Y;
                case 2:
                    return vector.Z;
                default:
                    return -1;
            }
        }
    }
    
    public class Collisions
    {
        public const int NUMDIM = 3;
        public const int MIDDLE = 2;
        public const int LEFT = 1;
        public const int RIGHT = 0;

        public static double BoxCollide(Vector3 origin, Vector3 dir, Vector3 invRay, BoxStruct rect)
        {
            Vector3 tvmin = (rect.Min - origin) * invRay;
            Vector3 tvmax = (rect.Max - origin) * invRay;

            float temp;
            if (tvmin.X > tvmax.X)
            {
                temp = tvmax.X;
                tvmax.X = tvmin.X;
                tvmin.X = temp;
            }
            if (tvmin.Y > tvmax.Y)
            {
                temp = tvmax.Y;
                tvmax.Y = tvmin.Y;
                tvmin.Y = temp;
            }
            if (tvmin.Z > tvmax.Z)
            {
                temp = tvmax.Z;
                tvmax.Z = tvmin.Z;
                tvmin.Z = temp;
            }

            double tmin = tvmin.X > tvmin.Y ? (tvmin.X > tvmin.Z ? tvmin.X : tvmin.Z) : (tvmin.Y > tvmin.Z ? tvmin.Y : tvmin.Z);
            double tmax = tvmax.X < tvmax.Y ? (tvmax.X < tvmax.Z ? tvmax.X : tvmax.Z) : (tvmax.Y < tvmax.Z ? tvmax.Y : tvmax.Z);

            // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
            if (tmax < 0)
            {
                return -1;
            }

            // if tmin > tmax, ray doesn't intersect AABB
            if (tmin > tmax)
            {
                return -1;
            }

            return tmin;
        }

    }
}
